import axios from 'axios'
import store from '@/store/index.js'
import { Message } from 'element-ui'
import router from '@/router'
// import router from '@/router'
const _axios = axios.create({
  baseURL: process.env.VUE_APP_BASE_API
})

// 请求拦截器

_axios.interceptors.request.use(
  (config) => {
    // 携带token
    config.headers.token = store.state.user.token

    return config
  },
  (error) => Promise.reject(error)
)

// 响应拦截
_axios.interceptors.response.use(
  (res) => {
    if (res.data.code === 200) {
      return res
    } else if (res.data.code === 206) {
      // token失效处理
      store.commit('user/logout')
      router.push('/login?redirect=' + window.location.href.split('#')[1]) // token在哪个页面失效时下次进入就是该页面
      Message.error('请重新登录')
      return Promise.reject(res.data)
    } else {
      Message.error(res.data.message)

      return Promise.reject(res.data)
    }
  },
  (error) => {
    return Promise.reject(error)
  }
)

export default _axios
